import { Spin } from 'antd';
import { MapT } from '@/utils/map';
import { SelectGroup } from '@/components';
import { SelectProps } from 'antd/lib/select';
import React, { useEffect, useState, useCallback, useRef } from 'react';
import styles from './styles.less';


type IProps = {
  defaultGroup?: MapT;
  service: (params: any) => Promise<any>;
} & SelectProps<any>;

const initLimit: number = 1000;

const SelectFetch = (props: IProps) => {
  const { service, defaultGroup = {} , ...rest} = props;

  const pageRef = useRef<number>(1);
  const totalRef = useRef<number>(0);
  const [group, setGroup] = useState<MapT>(defaultGroup);
  const [loading, setLoading] = useState<boolean>(false);
  const [showMore, setShowMore] = useState<boolean>(true);

  const fetchList = useCallback(async (current: number) => {
    const para = { page: current, limit: initLimit };
    setLoading(true);
    try {
      const {
        totalCount,
        list = [],
      } = await service(para);

      pageRef.current = current;
      totalRef.current = totalCount;
      list.forEach((item: any) => (
        group[item.id] = item.name
      ));
      setGroup({ ...group });
    }
    catch (e) {}
    setLoading(false);
  }, []);

  const onLoadMore = useCallback(() => {
    const totalPage = Math.ceil(totalRef.current / initLimit);
    if (pageRef.current >= totalPage) return setShowMore(false);
    pageRef.current += 1;
    fetchList(pageRef.current);
  }, []);

  useEffect(() => {
    fetchList(1);
  }, []);

  const dropdownRender = useCallback((menu: any) => {
    return (
      <React.Fragment>
        {menu}
        <div className={styles.load_more}>
          {loading ? <Spin spinning /> : (
            <a onClick={onLoadMore}>
              {showMore ? '点击加载更多' : '无更多数据~'}
            </a>
          )}
        </div>
      </React.Fragment>
    );
  }, [loading, showMore]);

  return (
    <SelectGroup
      {...rest}
      group={group}
      loading={loading}
      dropdownRender={dropdownRender}
    />
  );
};

export default SelectFetch;

